package com.tul.exercise.base.java8.stream.optional;

import com.tul.exercise.base.java8.stream.base.Artist;
import jdk.nashorn.internal.runtime.regexp.joni.constants.OPCode;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.Optional;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 *
 */
public class OptionalTest {
    @Test
    @DisplayName("Optional的简单操作")
    public void test01() {
        // Optional包裹对象
        String name = "tuliang";
        Optional<String> str = Optional.of(name);
        Assertions.assertEquals(name, str.get());
        Assertions.assertTrue(str.isPresent());


        // 空对象
        Optional empty = Optional.empty();
        Assertions.assertFalse(empty.isPresent());
        Optional alsoEmpty = Optional.ofNullable(null);
        Assertions.assertFalse(alsoEmpty.isPresent());


        // 非空对象
        Optional<Artist> artist = Optional.ofNullable(Artist.createArtist());
        Assertions.assertTrue(artist.isPresent());

    }

    @Test
    @DisplayName("Optional获取值")
    public void test02() {

        Person person = new Person();

        Car car = new Car();

        Insurance insurance = new Insurance();

        // insurance 设置为null
        car.setInsurance(Optional.ofNullable(null));
        person.setCar(Optional.ofNullable(car));
        String name = person.getCarInsuranceName(Optional.ofNullable(person));
        assertEquals(Insurance.UNKNOWN, name);


        // car 设置为null
        person.setCar(Optional.ofNullable(null));
        String name2 = person.getCarInsuranceName(Optional.ofNullable(person));
        assertEquals(Insurance.UNKNOWN, name2);


        String insuranceName = "insuranceName";
        insurance.setName(insuranceName);
        car.setInsurance(Optional.of(insurance));
        person.setCar(Optional.ofNullable(car));
        String name3 = person.getCarInsuranceName(Optional.ofNullable(person));
        assertEquals(insuranceName, name3);
    }
}
